package com.wanhe.viewconf.views.child;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.wanhe.base.model.base.Dish;
import com.wanhe.base.model.base.SallOutDish;
import com.wanhe.base.model.disgn.Event;
import com.wanhe.base.model.disgn.ViewEvent;
import com.wanhe.base.model.disgn.ViewItem;
import com.wanhe.base.model.holder.DishHolder;
import com.wanhe.base.model.holder.SallOutHolder;
import com.wanhe.base.util.ObjectUtil;
import com.wanhe.shoppingcart.manager.CartManager;
import com.wanhe.shoppingcart.manager.ICartChangeObserver;
import com.wanhe.shoppingcart.manager.ICartItem;
import com.wanhe.viewconf.R;
import com.wanhe.viewconf.ViewCreator;
import com.wanhe.viewconf.ViewOptions;
import com.wanhe.viewconf.views.child.interfaces.IBindingViewFunc;
import com.wanhe.viewconf.views.child.interfaces.ICounterViewFunc;
import com.wanhe.viewconf.views.child.interfaces.IViewReady;

/**
 * File Name:MealBookCounterView.java<br/>
 * Package Name:com.wanhe.viewconf.views.child.counter<br/>
 * Date:2017/7/4 16:58<br/>
 * author:chendeji<br/>
 * desc: 菜单页面上添加删除的控件<br/>
 * Copyright (c) 2017/7/4, 781571323@qq.com All Rights Reserved.
 */
public class MealBookCounterView extends MealBookChildItemView
		implements
			ICartChangeObserver ,
			ICounterViewFunc ,
			IViewReady ,
			IBindingViewFunc {

	public static final String	TAG				= "MealBookCounterView";
	private double				warmNum;
	private TextView			tv_count;
	private TextView			tv_reduce;
	private TextView			tv_plus;
	private ImageView			iv_reduce;
	private ImageView			iv_plus;
	private ImageView			iv_sallout;
	private int					mGroupItemId	= -1;

	public MealBookCounterView(Context context) {
		super(context);
		// TODO: 2017/7/5 需要设置他的扩展参数
		setExtendScale(ViewCreator.getInstance().getExtentionPt());
		initView(context);
		initEvent();
	}

	private View.OnClickListener plusListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			/**
			 *
			 * 需要做的功能：
			 * 1，调用购物车的加菜功能，将菜品数据传入
			 * 2，用户操作的日志记录，菜品数据传入
			 * 3，控件的信息进行暴露
			 *
			 * @author 陈德基
			 * @time 2017/7/5
			 *       16:37
			 */
			ViewCreator.getInstance().getViewOptions().getViewNormalClick().operationView(
					MealBookCounterView.this, ViewOptions.OnViewNormalClickListener.CLICK);

			if (mGroupItemId > 0) {
				/**
				 * 有绑定分组，需要先将信息发送给分组，让分组先做处理，然后回调，再执行加数量的操作
				 * 
				 * @author 陈德基
				 * @time 2017/8/2
				 *       16:28
				 */
				sendAddEvent2Group();
			} else {
				callSelfEvent("add");
			}
		}
	};

	private View.OnClickListener reduceListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			/**
			 *
			 * 需要做的功能：
			 * 1，调用购物车的减菜功能，将菜品数据传入
			 * 2，用户操作的日志记录，菜品数据传入
			 * 3，控件的信息进行暴露
			 *
			 * @author 陈德基
			 * @time 2017/7/5
			 *       16:45
			 */
			ViewCreator.getInstance().getViewOptions().getViewNormalClick().operationView(
					MealBookCounterView.this, ViewOptions.OnViewNormalClickListener.CLICK);
			callSelfEvent("dec");
		}
	};

	private void initEvent() {
		CartManager.getInstance().addCartObserver(this);
		if (ViewCreator.getInstance().isPlusIconUseText()) {
			tv_plus.setOnClickListener(plusListener);
			tv_reduce.setOnClickListener(reduceListener);
		} else {
			iv_plus.setOnClickListener(plusListener);
			iv_reduce.setOnClickListener(reduceListener);
		}
	}

	private void showPlusBtn() {
		if (ViewCreator.getInstance().isPlusIconUseText()) {
			tv_plus.setVisibility(VISIBLE);
		} else {
			iv_plus.setVisibility(VISIBLE);
		}
	}

	private void hidePlusBtn() {
		if (ViewCreator.getInstance().isPlusIconUseText()) {
			tv_plus.setVisibility(GONE);
		} else {
			iv_plus.setVisibility(GONE);
		}
	}

	private void hideSallout() {
		iv_sallout.setVisibility(GONE);
	}

	private void showSallout() {
		iv_sallout.setVisibility(VISIBLE);
	}

	private void showReduceBtn() {
		if (ViewCreator.getInstance().isPlusIconUseText()) {
			tv_reduce.setVisibility(VISIBLE);
		} else {
			iv_reduce.setVisibility(VISIBLE);
		}
	}

	private void hideReduceBtn() {
		if (ViewCreator.getInstance().isPlusIconUseText()) {
			tv_reduce.setVisibility(GONE);
		} else {
			iv_reduce.setVisibility(GONE);
		}
	}

	/**
	 * Methor Name:update<br/>
	 * Package Name:com.wanhe.viewconf.views.child.counter<br/>
	 * Date:2017/7/5 17:48<br/>
	 * author:chendeji<br/>
	 * desc: 更新数据<br/>
	 * Copyright (c) 2017/7/5, 781571323@qq.com All Rights Reserved.
	 *
	 * @param
	 * @return
	 */
	private void update() {
		SallOutDish sallOutDish = SallOutHolder.getInstance().get(this.mDish.getCh_dishno());
		if (ObjectUtil.checkObject(sallOutDish)) {
			setSalloutData(sallOutDish);
		} else {
			hideSallout();
			int count = CartManager.getInstance().getSameGuidItemCount(mDish.getDish_guid());
			if (count == 0) {
				showPlusBtn();
				hideReduceBtn();
				tv_count.setVisibility(GONE);
			} else {
				showReduceBtn();
				tv_count.setVisibility(VISIBLE);
				tv_count.setText(String.valueOf(count));
				tv_count.invalidate();
			}
		}
	}

	private void setSalloutData(SallOutDish sallOutDish) {
		if (ObjectUtil.checkObject(sallOutDish)) {
			this.warmNum = sallOutDish.getWarnNum();
			setSallout();
		}
	}

	public void setSallout() {
		if (warmNum == 0) {
			showSallout();
			hidePlusBtn();
			hideReduceBtn();
			tv_count.setVisibility(GONE);
		} else {
			hideSallout();
			int count = CartManager.getInstance().getSameGuidItemCount(mDish.getDish_guid());
			if (count == 0) {
				showPlusBtn();
				hideReduceBtn();
				tv_count.setVisibility(GONE);
			} else {
				showReduceBtn();
				tv_count.setVisibility(VISIBLE);
				tv_count.setText(String.valueOf(count));
				tv_count.requestLayout();
				tv_count.invalidate();
			}
		}
	}

	private void initView(Context context) {

		/**
		 * 重新对控制器进行构造，
		 * 父类是LinearLayout，可以直接读取布局文件，加载控件。
		 * 缺点：
		 * 效率会比较低，因为还需要花费读取布局文件转化为内存对象的步骤
		 * 优点：
		 * 代码简洁，布局比较简单。
		 *
		 * @author 陈德基
		 * @time 2017/7/24 11:22
		 */

		View inflatLayout = LayoutInflater.from(context).inflate(R.layout.counter_layout, null,
				false);

		iv_sallout = (ImageView) inflatLayout.findViewById(R.id.iv_sall_out_img);
		tv_count = (TextView) inflatLayout.findViewById(R.id.tv_center_count_txt);
		tv_reduce = (TextView) inflatLayout.findViewById(R.id.tv_left_reduce_btn);
		tv_plus = (TextView) inflatLayout.findViewById(R.id.tv_right_plus_btn);
		iv_reduce = (ImageView) inflatLayout.findViewById(R.id.iv_left_reduce_btn);
		iv_plus = (ImageView) inflatLayout.findViewById(R.id.iv_right_plus_btn);

		tv_count.setTypeface(ViewCreator.getInstance().getFontTypeface());
		tv_plus.setTypeface(ViewCreator.getInstance().getIconTypeface());
		tv_reduce.setTypeface(ViewCreator.getInstance().getIconTypeface());

		iv_sallout.setBackgroundDrawable(ViewCreator.getInstance().getSalloutDrawable());
		iv_reduce.setBackgroundDrawable(ViewCreator.getInstance().getCounterReduceDrawable());
		iv_plus.setBackgroundDrawable(ViewCreator.getInstance().getCounterPlusDrawble());

		if (ViewCreator.getInstance().isPlusIconUseText()) {
			tv_plus.setVisibility(VISIBLE);
		} else {
			iv_plus.setVisibility(VISIBLE);
		}

		this.addView(inflatLayout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.MATCH_PARENT));
	}

	@Override
	public int[] transpRect(double left, double top, double right, double bottom) {
		double oldWidth = right - left;
		double oldHeight = bottom - top;

		double newHeight = oldHeight * getExtendScale();

		double newWidth = oldWidth;

		double deltx = (newWidth - oldHeight) / 2;
		double delty = (newHeight - oldHeight) / 2;

		int[] newLocation = new int[4];
//		newLocation[0] = (int) (left - deltx);
//		newLocation[1] = (int) (top - delty);
//		newLocation[2] = (int) (newLocation[0] + newWidth);
//		newLocation[3] = (int) (newLocation[1] + newHeight);

		newLocation[0] = (int) left;
		newLocation[1] = (int) top;
		newLocation[2] = (int) right;
		newLocation[3] = (int) bottom;

		return newLocation;
	}

	@Override
	public void bindData(Dish dish) {
		super.bindData(dish);
		if (ObjectUtil.checkObject(dish)) {
			update();
		}
	}

	@Override
	public void setViewColor(String color) {
		super.setViewColor(color);
		tv_count.setTextColor(getColor());
		if (ViewCreator.getInstance().isPlusIconUseText()) {
			tv_plus.setTextColor(getColor());
			tv_reduce.setTextColor(getColor());
		}
	}

	@Override
	public boolean isNeedUpdate() {
		return true;
	}

	@Override
	public void onCartChanged(boolean isAdd) {

		ICartItem currentItem = CartManager.getInstance().getCurrentItem();
		if (ObjectUtil.checkObject(this.mDish)
				&& this.mDish.getDish_guid().equals(currentItem.getDishGuid())) {
			// 获取控件的位置，然后可以将这些数据对外暴露，做一些其他的事情。
			int[] xy = getViewXY();
			int width = getMeasuredWidth();
			int height = getMeasuredHeight();
			int x = xy[0] + width / 2;
			int y = xy[1] + height / 2;

			setViewStatu(VIEW_DIRTY);
			update();
			/**
			 * 数量文本显示有时候会显示不够用，这里需要手动的去重新布局文本控件的大小才能显示全文本
			 *
			 * @author 陈德基
			 * @time 2017/8/1 11:30
			 */
			requestLayout();
			// TODO: 2017/7/6 需要将控件的坐标位置暴露出去，外部可以进行一些特效的显示
			ViewCreator.getInstance().getViewOptions().getViewNormalClick()
					.cartChangeReceiveXY(this, x, y);

			if (isAdd){
				sendEventWithKey("add");
			}

		}
	}

	@Override
	public void set(Event event, ViewEvent.Coor coor) {
		super.set(event, coor);
		Event.ArgsBean args = event.getArgs();
		Dish dish = DishHolder.getInstance().get(args.getDishID());
		if (ObjectUtil.checkObject(dish)) {
			bindData(dish);
		}
	}

	@Override
	public void add(Event event, ViewEvent.Coor coor) {
		// 加减号的操作对外暴露
		ViewCreator.getInstance().getViewOptions().getCounterViewClick()
				.plus(MealBookCounterView.this, MealBookCounterView.this.mDish);
		sendEvent(event);
	}

	@Override
	public void dec(Event event, ViewEvent.Coor coor) {
		// 加减号的操作对外暴露
		ViewCreator.getInstance().getViewOptions().getCounterViewClick()
				.reduce(MealBookCounterView.this, MealBookCounterView.this.mDish);
		sendEvent(event);
	}

	/**
	 * Methor Name:发送消息给分组<br/>
	 * Package Name:com.wanhe.viewconf.views.child<br/>
	 * Date:2017/8/2 16:34<br/>
	 * author:chendeji<br/>
	 * desc: <br/>
	 * Copyright (c) 2017/8/2, 781571323@qq.com All Rights Reserved.
	 *
	 * @param
	 * @return
	 */
	private void sendAddEvent2Group() {
		if (!ObjectUtil.checkObject(this.mDish))
			return;
		Event e = new Event();
		e.setCid(this.mGroupItemId);
		e.setCop("add");
		sendEvent(e);
	}

	@Override
	public void ready(Event event, ViewEvent.Coor coor) {
		event.getArgs().setCusObj(this);
		sendEvent(event);
	}

	@Override
	public void bind(Event event, ViewEvent.Coor coor) {
		/**
		 * TODO 测试回调绑定数据的功能
		 *
		 * @author 陈德基
		 * @time 2017/7/29 18:07
		 */
		if (ObjectUtil.checkObject(event)) {
			mGroupItemId = event.fromCid;
			String cus = event.getArgs().getCus();
			ViewItem.CountRule rule = new Gson().fromJson(cus, ViewItem.CountRule.class);
			ViewItem.CountRule custom = this.mItem.getCustom();
			this.mItem.setCustom(rule);
		}
	}
}
